
var model = require('model');

function login(callback) {
    wx.login({
        success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            var code = res.code;

            wx.getUserInfo({
                success: res => {
                    // 可以将 res 发送给后台解码出 unionId
                    //console.log(res.userInfo.nickName);
                    //app.globalData.userInfo = res.userInfo

                    // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                    // 所以此处加入 callback 以防止这种情况
                    // if (app.userInfoReadyCallback) {
                    //     app.userInfoReadyCallback(res)
                    // }

                    var encryptedData = res.encryptedData;
                    var iv = res.iv;
                    var rawData = res.rawData;
                    var signature = res.signature;
                    var userInfo = res.userInfo;

                    model.request({
                        action: 'login',
                        method: 'POST',
                        data: {
                            code: code,
                            rawData: rawData,
                            signature: signature,
                            encryptedData: encryptedData,
                            iv: iv,
                            portrait: userInfo.avatarUrl,
                            wechaname: userInfo.nickName,
                            sex: userInfo.gender
                        },
                        header: {
                            "Content-Type": "application/x-www-form-urlencoded"
                        },
                        success: function (res) {
                            console.log(res);
                            if (callback) {
                                callback({
                                    userInfo:userInfo,
                                    session3rd:res.data.session3rd,
                                    wecha_id:res.data.wecha_id
                                });
                            }
                        }
                    });
                }
            })
        }
    })
}

module.exports = {
    login:login
}